<template>
  <div>
    <el-row >
      <el-col :span="23">
      <el-form ref="elForm" 
      :model="formData"
       :rules="rules" 
      size="medium"
        class="form-body"
        label-suffix="："
       label-width="150px">
        
        <h3 style="margin-top:0" class="form-section-title">基本信息</h3>
<!--  -->
          <el-form-item label="投放名称" prop="adverteName">
            <el-input v-model="formData.adverteName" placeholder="投放名称投放名称" clearable
              prefix-icon='el-icon-document-add' :style="{width: '60%'}"></el-input>
          </el-form-item>
      
          <el-form-item label="计费方式" prop="caculateMethod">
            <el-radio-group v-model="formData.caculateMethod" size="medium">
              <el-radio v-for="(item, index) in caculateMethodOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-radio>
            </el-radio-group>

                 <!-- 提示信息 -->
                <el-tooltip class="item" effect="light"  placement="right">
                    <div  slot="content" style="width:200px; background:#fff;"> 
                      <p>计费方式是广告买卖双方之间进行费用核算的方式，常用三种计费方式：<br/></p>

                    <ul>
                        <li>每日费用(CPD)：按天进行计费；</li>
                        <li>每千次展示费用(CPM)：按每千次展示进行计费；</li>
                        <li>每次点击费用(CPC)：按每次点击进行计费。</li>
                    </ul>
                    </div>
                    <span class="icon-tips el-icon-question"></span>
                </el-tooltip>
                <!--  -->

          </el-form-item>
     
          <el-form-item label="单价" prop="perPrice">
            <el-input v-model="formData.perPrice" placeholder="请输入单价"
             clearable :style="{width: '20%'}">
            </el-input> 
            <!-- 广告价格单位 -->
            <span> {{priceUnit}}</span>
          </el-form-item>
        
           <el-form-item label="载体类型" prop="adtype">
                <!-- <el-select v-model="formData.adtype"
                 placeholder="请选择" 
                 :style="{width: '30%'}">
                  <el-option v-for="(item, index) in adtypeOptions" :key="index" :label="item.label"
                    :value="item.value" :disabled="item.disabled"></el-option>
                </el-select> -->
                <el-radio-group v-model="formData.adtype" size="medium">
                    <el-radio v-for="(item, index) in adtypeOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{item.label}}</el-radio>
                  </el-radio-group>

              </el-form-item>
              
                  
               
          <el-row >
            
            <el-col :span="24">
              <el-form-item label="选择广告位" prop="placeIds">
                 <p class="label-tips">请选择相同载体类型，类型，尺寸的广告位进行广告投放</p>
              </el-form-item>
            </el-col>
            
          <!-- 多选择广告位 -->
          <el-col :span="24">
             <el-form-item label="">
               <!-- 选择广告位组件 ，最终返回选择好的广告id数组 -->
              <set-place-mutil-select
                v-on:onchangeselect="OnChangeSelect"
                :result-ids="formData.placeIds"
               :plattype="formData.adtype"></set-place-mutil-select>
             </el-form-item>
          </el-col>

          </el-row>
          <!-- 优先级 -->
            <el-form-item label="优先级" prop="priority">
               <el-select v-model="formData.priority"
                 placeholder="请选择"  :style="{width: '10%'}">
                  <el-option v-for="(item, index) in priorityOptions" :key="index" :label="item.label"
                    :value="item.value" ></el-option>
                </el-select> 
                <el-select v-model="formData.priorityLeve" 
                 :style="{width: '10%'}"
                size="medium">
                    <el-option  v-for="(item, index) in priorityLeveOptions" :key="index" :label="item.label"
                     :value="item.value" ></el-option>
                 </el-select> 
                <span >1（最高）-29（最低）</span>
                <!-- 设置权重  -->
                <div style="display:inline-block;width:100px;margin-left:20px;">
                  
                     <el-checkbox v-model="formData.weight" label="1" > 设置权重 </el-checkbox>
                  
                </div>
                  <!-- /操作提示 -->
                <el-tooltip class="item" effect="light"  placement="right">
                    <div  slot="content" style="width:200px; background:#fff;"> 
                              <p>1. 数字越大则权重越高。</p>
                              <p>2. 当两个投放的优先级相同时，高权重的广告展现概率更高。
                                  例如，A和B两个相同优先级的投放权重分别为m和n，
                                  则A和B的展示概率分别为m/(m+n)、n/(m+n)。</p>
                          </div>
                    <span class="icon-tips el-icon-question"></span>
                </el-tooltip>
              
              <!--  -->
               <el-select v-if="formData.weight" v-model="formData.weightLeve" size="medium" :style="{width: '10%'}">
                    <el-option  v-for="(item, index) in weightLeveOptions" :key="index" :label="item.label"
                     :value="item.value" ></el-option>
                 </el-select> 
             

              </el-form-item>
          <!--  -->
       <h3 class="form-section-title">投放设置</h3>
<!--  --> 
              <el-form-item label="投放时间" prop="proid">
                <el-radio-group v-model="formData.proid" size="medium">
                  <el-radio   :label="1" >连续时间</el-radio>
                  <el-radio   :label="2" >不连续时间</el-radio>
                </el-radio-group>
                    <!-- 提示信息 -->
                <el-tooltip class="item" effect="light"  placement="right">
                    <div  slot="content" style="width:200px; background:#fff;"> 
                      <p> 你可以指定投放的起止时间，和只在特定时段展现，精确到小时。
                          若你不需要广告立即展现，也可指定一个未来的时间。  </p>
                    </div>
                    <span class="icon-tips el-icon-question"></span>
                </el-tooltip>
                <!--  -->
                <!-- 连续时间 设置 -->
                <el-row v-if="formData.proid==1">
                    <el-col :span="12"  class="dropPanel">
                    
                          <el-col :span="15">
                            <el-form-item label="开始时间" prop="startday">
                                <el-date-picker v-model="formData.startday" 
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                :style="{width: '90%'}" placeholder="请选择日期" ></el-date-picker>
                            </el-form-item>
                            </el-col>
                            <el-col :span="9">
                            <el-form-item label-width="0" prop="starttime">
                                <el-time-picker v-model="formData.starttime"
                                 format="HH:mm:ss" value-format="HH:mm:ss"
                                :picker-options='{"selectableRange":"00:00:00-23:59:59"}'
                                 :style="{width: '90%'}"
                                placeholder="请选择时间" clearable></el-time-picker>
                            </el-form-item>
                            </el-col>
                            <!--  -->
                    <el-col :span="24"> 
                <el-form-item label="结束时间" prop="hasendtime">
                <el-radio-group v-model="formData.hasendtime" size="medium">
                  <el-radio   :label="0" >不限结束时间</el-radio>
                  <el-radio   :label="1" >设定结束时间</el-radio>
                </el-radio-group>            
                </el-form-item>
                    </el-col>
                    <!--  -->
                      <el-col v-if="formData.hasendtime==1"  :span="24">
                         <el-col :span="15">
                            <el-form-item label="选择" prop="endday">
                                <el-date-picker v-model="formData.endday"
                                 format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                :style="{width: '90%'}" placeholder="请选择日期" ></el-date-picker>
                            </el-form-item>
                            </el-col>
                          <el-col :span="9">
                            <el-form-item label-width="0" prop="endtime">
                                <el-time-picker v-model="formData.endtime" 
                                format="HH:mm:ss" value-format="HH:mm:ss"
                                :picker-options='{"selectableRange":"00:00:00-23:59:59"}'
                                 :style="{width: '90%'}"
                                placeholder="请选择时间" clearable></el-time-picker>
                            </el-form-item>
                            </el-col>
                        </el-col>
                    </el-col>
                </el-row>
                <!-- 不连续时间设置 -->
                <el-row  v-if="formData.proid==2">
                    <el-col :span="12"  class="dropPanel">
                        <el-form-item label="已选日期" prop="proidRows">
                            <el-input
                            v-model="formData.proidRows"
                            autocomplete="off"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 5 }"
                            placeholder="不连续时间"
                            :readonly="true"
                            :style="{ width: '100%', 'margin-bottom':'7px' }"
                          ></el-input>
                        </el-form-item>
                       <el-form-item label="选择日期" prop="proidRows">  
                           <el-date-picker
                              type="dates"
                              v-model="formData.proidRows"
                              value-format="yyyy-MM-dd"
                               :style="{ width: '100%' }"
                              placeholder="选择一个或多个日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
              </el-form-item>
          <!--  -->
       <h3 class="form-section-title">策略设置</h3>

        <el-form-item label="地域定向" prop="limitArea">
                <el-radio-group v-model="formData.limitArea" size="medium">
                  <el-radio   :label="0" >不限制地域</el-radio>
                  <el-radio   :label="1" >定向地域</el-radio>
                  <el-radio   :label="2" >屏蔽地域</el-radio>
                </el-radio-group>
        
        </el-form-item>


          <el-form-item label="投放上限" prop="topLimit">
            <el-checkbox-group v-model="formData.topLimit" size="medium">
              <el-checkbox v-for="(item, index) in topLimitOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-checkbox>
            </el-checkbox-group>

            <!--  -->
            <el-form-item v-if="showTopLimitNum" label="最多展现">
              <el-input v-model="formData.topLimitNum" placeholder=""  size="mini"
               :style="{width: '90px'}"></el-input> <span> 次</span>
            </el-form-item>
            <!--  -->

          </el-form-item>
        
          <el-form-item label="每日投放量" prop="dayLimit">
            <el-checkbox-group v-model="formData.dayLimit" size="medium">
              <el-checkbox v-for="(item, index) in dayLimitOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-checkbox>
            </el-checkbox-group>
             <!--  -->
            <el-form-item  v-if="showDayLimitNum" label="每天展现">
              <el-input v-model="formData.dayLimitNum" placeholder=""  size="mini"
               :style="{width: '90px'}"></el-input> <span> 次</span>
            </el-form-item>
            <!--  -->

          </el-form-item>
      
        
          <el-form-item label="频次控制" prop="frequency">
            <el-checkbox-group v-model="formData.frequency" size="medium">
              <el-checkbox v-for="(item, index) in frequencyOptions" :key="index" :label="item.value"
                :disabled="item.disabled">{{item.label}}</el-checkbox>
            </el-checkbox-group>
            <!--  -->
            <el-form-item   v-if="showFrequencyNum" label="最多展现次数">
              <el-input v-model="formData.frequencyNum" placeholder=""  size="mini"
               :style="{width: '90px'}"></el-input> <span> 次</span>
            </el-form-item>
            <!--  -->
          </el-form-item>
          <!--  -->
       <h3 class="form-section-title">广告媒体</h3>
      
          <el-form-item label="媒体轮换" prop="rangeMethod">
            <el-select v-model="formData.rangeMethod"
             placeholder="请选择媒体轮换"
               :style="{width: '20%'}">
              <el-option v-for="(item, index) in rangeOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select> 
             <el-tooltip class="item" effect="light"  placement="right">
              <div  slot="content" style="width:200px; background:#fff;"> <p><strong>均匀</strong>：每条广告物料获得均等的展现概率。</p>
               <br><p><strong>手动权重</strong>：手工设置广告物料的权重，高权重的广告物料展现概率更高。
               例如，广告A中仅有两个广告物料C和D，C和D的权重分别为m和n，则C和D的展示概率分别为m/(m+n)、n/(m+n)。</p>
               <br> 
               <p><strong>幻灯片轮换</strong>：以幻灯片播放的方式在一次浏览中依次展现全部广告物料，
               只支持文字和图片广告物料。</p><br>
               <p><strong>微轮播</strong>：针对单个cookie，物料A、B、C按顺序循环轮换。
               <br> 首次展示：随机选择，若首次显示B<br> 刷新1次：C<br> 刷新2次：A<br> 刷新3次：B<br>
                按此顺序循环轮换。</p></div>
             <span class="icon-tips el-icon-question"></span>
             </el-tooltip>
            <!--  -->
            <el-row v-if="showRangeNum">
            <el-col :span="8" class="dropPanel">
            <el-form-item  label="轮换时间间隔">
              <el-input v-model="formData.rangeNum" placeholder=""  size="mini"
               :style="{width: '90px'}"></el-input> <span> 秒</span>
              
            </el-form-item>
            </el-col>
            </el-row>
            <!--  -->
          </el-form-item>
         
      
       <el-form-item label="广告媒体" prop="medias">
           
             <!--  -->
          <el-form-item size="mini" >
            <el-button type="primary" @click="handelNewMediasDrawer">新建广告物料</el-button>
            <!-- <el-button type="primary" @click="openSelectMeidas">从广告库选择</el-button> -->
            <el-button type="primary" @click="handelSelectMediasDrawer">从物料库选择</el-button>
          </el-form-item>

          <el-row>
              <el-col :span="22">
                <!-- 已经选择的物料 -->
                <table-medias-list
                 :show-delete="true"
                 :select-medias-list="selectMediasList">
                </table-medias-list>
              </el-col>
            </el-row>

       </el-form-item>
        
    <!-- 打开新抽屉 选择广告媒体或者新建广告媒体 -->
       <el-drawer
          ref="selectMediasDrawer"
          :title="drawerTitle"
          :append-to-body="true"
          :visible.sync="openMediasDrawer"        
          :show-close="true"
          :before-close="handleSelectMediasDrawerClose"
          :wrapper-closable='false'
          :destroy-on-close="true"
          :with-header="true"
          size="85%">
           <div class="formBox" >
             <!-- 新建物料drawer -->
              <medias-add-form v-if="drawerAdd"
              v-on:onclosedrawer="onCloseDrawer" >
              </medias-add-form>
              <!-- 从物料库选择 -->
              <select-medias v-else

               v-on:onclosedrawer="onCloseDrawer">
              </select-medias>
           </div>
        </el-drawer>

       <!--  -->

          <el-form-item size="large" class="form-submit-panel">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm"> 关闭  </el-button>
          </el-form-item>
        
      </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import SelectMedias from './SelectMedias.vue';
import TableMediasList from './TableMediasList.vue';
export default {
  components: {TableMediasList, SelectMedias},
  props: ['idadverte', 'idcopy'],
  data() {
    // 自定义投放时间设置 验证规则
    var checkProid = (rule, value, callback)=>{
      if(this.formData.proid ==1){
          if(!this.formData.startday || !this.formData.starttime ){
           callback(new Error( '请选择投放开始时间' ));            
          }
          if(this.formData.hasendtime==1){
            if(!this.formData.endday || !this.formData.endtime ){
               callback(new Error( '请选择投放结束时间' ));              
            }
          }
        }else{
          if(!this.formData.proidRows){
              callback(new Error('请选择投放时间段'));   
             
          }
        }
        callback( ) ;// 一定要调用否则 验证不通过
    }
    return {
      formData: {
        id:0,
        adverteName: '',
        caculateMethod: 3,
        perPrice: '',
        adtype: 1,
        placeIds: '', // 广告位的ids 字符串 ,1,2,3……,
        // keyword: '',       
        topLimit: [],
        topLimitNum:0,        
        dayLimit: [],
        dayLimitNum:0,
        frequency: [],
        frequencyNum:0,
        rangeMethod: 1, // 媒体轮换方式
        rangeNum: 0, // 轮换次数
        medias: '',
        proid: 1,  // 投放时间 1 连续时间，2 不连续时间
        startday:'',
        starttime:'',
        hasendtime:0, // 0 不限制结束时间 ，1 限制结束时间
        endday:'',
        endtime:'', 
        proidRows:'', // 不连续时间       
        limitArea:0 ,// 不限制地域 1 地域定向 2屏蔽地域
        priority:1, //优先级等级
        priorityLeve:1, //优先级等级数字
        weight: false, //设置优先级
        weightLeve: 1
      },
      // 打开选择广告媒体抽屉
      openMediasDrawer: false,
      priceUnitOptions: { "1":'元/CPD',"2":'元/CPM',"3":'元/CPC'},
      selectMediasList:[], //已经选中的物料数据
      drawerAdd: true, // 默认打开新建物料drawer
      drawerTitle: "新建广告物料",
      rules: {
        adverteName: [{
          required: true,
          message: '投放名称投放名称',
          trigger: 'blur'
        }],
        caculateMethod: [{
          required: true,
          message: '计费方式不能为空',
          trigger: 'change'
        }],
        perPrice: [{
          required: true,
          message: '请输入单价',
          trigger: 'blur'
        }],
        adtype: [{
          required: true,
          message: '平台',
          trigger: 'change'
        }],
        placeIds: [{
          required: true,          
          message: '请选择相同类型和尺寸的广告位',
          trigger: 'change'
        }],
        
        proid: [{
          required: true,
          validator: checkProid,
          message: '投放时间不能为空',
          trigger: ["blur", "change"]
        }] 
  
      },
      caculateMethodOptions: [{
        "label": "CPD",
        "value": 1
      }, {
        "label": "CPM",
        "value": 2
      }, {
        "label": "CPC",
        "value": 3
      }],
      adtypeOptions: [{
        "label": "PC",
        "value": 1
      }, {
        "label": "移动网页",
        "value": 2
      }, {
        "label": "APP应用",
        "value": 3,
      }, {
        "label": "视频",
        "value": 4,
      }],
      priorityOptions:[
        {"value":1,"label":"独占"},
      {"value":2,"label":"优先"},
      {"value":3,"label":"标准"},
      {"value":4,"label":"补余"}],
     
      topLimitOptions: [{
        "label": "设置投放上限",
        "value": 1
      }],
      dayLimitOptions: [{
        "label": "限制每日投放数量",
        "value": 1
      }],
      frequencyOptions: [{
        "label": "限制对独立访客的展现次数",
        "value": 1
      } ],
      rangeOptions: [{
        "label": "均匀",
        "value": 1
      }, {
        "label": "手动权重 ",
        "value": 2
      }, {
        "label": "幻灯片轮换 ",
        "value": 3
      },{
        "label": "微轮播 ",
        "value": 4
      }],
    }
  },
  computed: {
      //编辑 时id>0
    row(){
      return this.idadverte ? this.idadverte :0;
    }, 
    // 拷贝数据是
    rowCopy(){
      return this.idcopy ? this.idcopy : 0;
    },
    priorityLeveOptions : function(){
        if(this.formData.priority==1){
          return [{"vlaue":1,"label":"1"}]
        }
        if(this.formData.priority==2){
          var tmp = [];
          for(var i=2; i<12;i++){
              tmp.push({ "value":i, "label":  i  });
          }
          return tmp;          
        }
        if(this.formData.priority==3){
          var tmp = [];
          for(var i=12; i<22;i++){
              tmp.push({ "value":i, "label":  i  });
          }
          return tmp;          
        }
       if(this.formData.priority==4){
          var tmp = [];
          for(var i=22; i<30;i++){
              tmp.push({ "value":i, "label":   i  });
          }
          return tmp;          
        }
    },
    weightLeveOptions:function(){     
          var tmp = [];
          for(var i=1; i<=10;i++){
              tmp.push({ "value":i, "label":   i  });
          }
          return tmp;          
       
    },
     // 价格单位
      priceUnit:function(){
          return this.priceUnitOptions[ this.formData.caculateMethod ];
      },
      // 是否显示每日最多展现次数
      showTopLimitNum(){
        return this.formData.topLimit.length>0;
      },
      showDayLimitNum(){
        return this.formData.dayLimit.length>0;
      },
      showFrequencyNum(){
        return this.formData.frequency.length>0;
      },
      showRangeNum(){
        return this.formData.rangeMethod == 3;
      }
  },
  watch: {
    "formData.priority":function (val,oldval){
        if(val ==1){
          this.formData.priorityLeve = 1;
        }
        if(val ==2){
          this.formData.priorityLeve = 7;
        }
        if(val ==3){
          this.formData.priorityLeve = 17;
        }
        if(val ==4){
          this.formData.priorityLeve = 29;
        }
    }
  },
  created() {
    if(this.row){ // 传递了一个 对象过来，id表示整个 数据表记录行
       // console.log(this.id)
       for(var i in this.formData){
         if(this.row[i]){
           this.formData[i] = this.row[i];
         }
       }
       //编辑的时候
       //this.formData = this.id;
      this.formData.topLimit = this.row.topLimitNum>0 ?[1]: [];
      this.formData.frequency = this.row.frequencyNum>0 ?[1]: [];
      this.formData.dayLimit = this.row.dayLimitNum>0 ?[1]: [];
      this.formData.weight = this.row.weightLeve>0 ? true:  false;
       //编辑是 更新
    }
    if(this.rowCopy){
       // 传递了一个 对象过来，id表示整个 数据表记录行
       for(var i in this.formData){
         if(this.rowCopy[i]){
           this.formData[i] = this.rowCopy[i];
         }
       }
      this.formData.topLimit = this.rowCopy.topLimitNum>0 ?[1]: [];
      this.formData.frequency = this.rowCopy.frequencyNum>0 ?[1]: [];
      this.formData.dayLimit = this.rowCopy.dayLimitNum>0 ?[1]: [];
      this.formData.weight = this.row.weightLeve>0 ? true:  false;
      this.formData.id = 0; 
       // 复制是 新增
    }
    //获取物料列表
    PlaceAPI.getAllMedias(1, 100, {ids: this.formData.medias}).then((data) => {
              // 把必须要的参数赋值进去
              this.selectMediasList = data.data;
      })
  },
  mounted() {},
  methods: {
    handelNewMediasDrawer(){
      this.openMediasDrawer = true;
      this.drawerAdd = true;
      this.drawerTitle = "新建广告物料";
    },
    handelSelectMediasDrawer(){
        this.openMediasDrawer = true;
        this.drawerAdd  =false;
        this.drawerTitle = "从广告物料库选择";
    },
    // 广告位选择后返回选中的广告位ID数组
    OnChangeSelect( data){
      //if(data.ids.length>1){
          this.formData.placeIds =  data.ids.join(',') ;
     // } 
      
    },
    submitForm() {

      this.loading = true;
      // 选中的物料信息
      if(this.selectMediasList){
          var tmp = [];
          for(var m in this.selectMediasList){
            tmp.push(this.selectMediasList[m]['id'])             
          }
         
          this.formData.medias = tmp.join(",");
      }
      //  console.log(this.formData)
            // 物料选中 的赋值 
      this.$refs['elForm'].validate(valid => {
        if (!valid) return;
       
        // console.log(this.formData)
        //  提交数据到接口，更新和新建通过 formData.id > 0 来区别
         PlaceAPI.createAdverte(this.formData).then((data)=>{
            this.loading = false;
            this.$message({ message: data.msg, type: "success" });
            // 触发关闭Drawer 侧滑层 关闭
            this.$emit("onclosedrawer",{ from: 'submit'})
         })
         
      })
    },
    resetForm() {
      this.$emit("onclosedrawer",{ from: ''})
    },
    // 在 关闭 选择物料库 或者 新建物料的 drawer 抽屉层时：
    onCloseDrawer(e) {

            // console.log(e)
            //e == { from: "submit"}
            this.submit = e.from;
            this.$refs.selectMediasDrawer.closeDrawer();
            //把新建的物料 或者选择的物料 添加到物料列表
            if(!e.row.hasOwnProperty("content")){
              e.row["content"] = {
                type: e.row.type
              }
             if(e.row.hasOwnProperty(e.row.type)){
                  e.row["content"][e.row.type] = e.row[e.row.type]
             }
             //新建的时候 content 没有这个对象
            }
            this.selectMediasList.push( e.row);
       
        },
    // 关闭选择广告媒体抽屉
    handleSelectMediasDrawerClose(done){
          done();
          return;        
    }
  }
}

</script>
<style>
</style>
